package com.gearbox.core.service.impl;

import com.gearbox.core.model.shell.ShellResult;
import com.gearbox.core.service.SystemResourceService;
import com.gearbox.core.util.CmdExecuteResultAssertion;
import com.gearbox.core.util.ShellExecutor;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Locale;

@Component
public class LinuxSystemResourceService implements SystemResourceService {
    @Override
    public boolean isInEtcHosts(String keyword) {
        List<String> hostRecords = getHostRecords();
        for (String line : hostRecords) {
            if (line.contains(keyword)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void addEtcHostsRecord(String host, String ip) {
        String cmd = String.format(Locale.ROOT, "echo \"%s %s\" >> /etc/hosts", ip, host);
        ShellResult result = ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result,
            String.format(Locale.ROOT, "run [%s] failed", result.getCommandLine()));
    }

    public static List<String> getHostRecords() {
        String cmd = "cat /etc/hosts";
        ShellResult result =  ShellExecutor.runCommand(cmd);
        CmdExecuteResultAssertion.assertError(result,
            String.format(Locale.ROOT, "run [%s] failed", result.getCommandLine()));
        return result.getReturnValues();
    }
}
